<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件的冒泡与捕获</title>
  </head>
  <body>
    <div class="grandpa">
      <div class="parent">
        <button class="childBtn">点击事件</button>
      </div>
    </div>

    <script>
      var grandpa = document.getElementsByClassName('grandpa');
      var parent = document.getElementsByClassName('parent');
      var childBtn = document.getElementsByClassName('childBtn');

      // addEventListener 方法来注册事件处理程序，可选的第三个参数(boolean类型)可用来指定事件传播阶段。默认为false，表示采用事件冒泡，可设置为true，采用事件捕获的方式。
      // 默认是采用事件冒泡的传播方式，依次触发 childBtn, parent, grandpa 事件回调函数
      //   grandpa[0].addEventListener('click', () => {
      //     console.log('1. grandpa div had clicked');
      //   });

      //   parent[0].addEventListener('click', () => {
      //     console.log('2. parent div had clicked');
      //   });

      //   childBtn[0].addEventListener('click', () => {
      //     console.log('3. child button had clicked');
      //   });

      // 事件捕获，依次触发 grandpa, parent, childBtn 事件回调函数
      grandpa[0].addEventListener(
        'click',
        () => {
          console.log('1. grandpa div had clicked');
        },
        true
      );

      parent[0].addEventListener(
        'click',
        () => {
          console.log('2. parent div had clicked');
        },
        true
      );

      childBtn[0].addEventListener(
        'click',
        () => {
          console.log('3. child button had clicked');
        },
        true
      );
    </script>
  </body>
</html>
